const app = getApp();

Page({
  data: {
    todayVisitors: 0,
    todayFans: 0,
    shopStatus: 'closed', // 'open' 出摊中, 'rest' 休息中, 'closed' 已关闭
    location: {
      latitude: 0,
      longitude: 0,
      name: '',
      address: ''
    },
    markers: [],
    shopInfo: {
      name: '',
      description: '',
      logo: ''
    },
    isLogin: false,
    hasShop: false,
    showDataPanel: false
  },

  onLoad: function() {
    // 检查登录状态
    if (!app.globalData.isLogin) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    // 检查是否有店铺
    if (!app.globalData.hasShop) {
      wx.redirectTo({
        url: '/pages/shop/create/create'
      });
      return;
    }
    
    // 初始化数据
    this.setData({
      isLogin: app.globalData.isLogin,
      hasShop: app.globalData.hasShop,
      shopInfo: app.globalData.shopInfo || {},
      shopStatus: app.globalData.shopStatus
    });
    
    // 获取今日访客和粉丝数据
    this.getVisitorStats();
    // 更新位置信息
    this.updateLocationDisplay();
  },

  onShow: function() {
    // 页面显示时刷新数据
    if (!app.globalData.isLogin) {
      wx.redirectTo({
        url: '/pages/login/login'
      });
      return;
    }
    
    if (!app.globalData.hasShop) {
      wx.redirectTo({
        url: '/pages/shop/create/create'
      });
      return;
    }
    
    // 更新状态
    this.setData({
      isLogin: app.globalData.isLogin,
      hasShop: app.globalData.hasShop,
      shopInfo: app.globalData.shopInfo || {},
      shopStatus: app.globalData.shopStatus
    });
    
    // 更新位置信息
    this.updateLocationDisplay();
    // 更新访客数据
    this.getVisitorStats();
  },

  updateLocationDisplay: function() {
    // 从 app.globalData 获取位置信息
    const location = app.globalData.location;
    if (location.latitude && location.longitude) {
      this.setData({
        location: location,
        markers: [{
          id: 1,
          latitude: location.latitude,
          longitude: location.longitude,
          width: 30,
          height: 30,
          callout: {
            content: this.data.shopInfo.name || '我的店铺',
            display: 'ALWAYS'
          }
        }]
      });
    } else {
      // 如果 app.globalData 中没有位置信息，尝试获取
      app.getLocation();
      setTimeout(() => {
        this.updateLocationDisplay();
      }, 1000);
    }
  },

  getShopStatus: function() {
    // 从服务器获取店铺状态
    wx.request({
      url: 'https://api.example.com/shop/status',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data && res.data.status) {
          const status = res.data.status;
          this.setData({ shopStatus: status });
          app.globalData.shopStatus = status;
        }
      }
    });
  },

  getVisitorStats: function() {
    // 从服务器获取访客和粉丝数据
    wx.request({
      url: 'https://api.example.com/shop/statistics/today',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data && res.data.statistics) {
          const stats = res.data.statistics;
          this.setData({
            todayVisitors: stats.visitors || 0,
            todayFans: stats.fans || 0
          });
          app.globalData.todayVisitors = this.data.todayVisitors;
          app.globalData.todayFans = this.data.todayFans;
        }
      },
      fail: () => {
        // 模拟数据（仅用于开发测试）
        this.setData({
          todayVisitors: 30,
          todayFans: 10
        });
        app.globalData.todayVisitors = this.data.todayVisitors;
        app.globalData.todayFans = this.data.todayFans;
      }
    });
  },

  setStatusOpen: function() {
    // 检查是否实名认证
    if (!app.globalData.isVerified) {
      wx.showModal({
        title: '实名认证',
        content: '开始营业前需要完成实名认证',
        confirmText: '去认证',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/verification/verification'
            });
          }
        }
      });
      return;
    }
    
    // 已认证，可以正常开始营业
    this.setData({ shopStatus: 'open' });
    app.updateShopStatus('open', (success) => {
      if (success) {
        wx.showToast({
          title: '已设置为出摊中',
          icon: 'success'
        });
      }
    });
  },

  setStatusRest: function() {
    this.setData({ shopStatus: 'rest' });
    app.updateShopStatus('rest', (success) => {
      if (success) {
        wx.showToast({
          title: '已设置为休息中',
          icon: 'success'
        });
      }
    });
  },
  
  setStatusClosed: function() {
    this.setData({ shopStatus: 'closed' });
    app.updateShopStatus('closed', (success) => {
      if (success) {
        wx.showToast({
          title: '已设置为已关闭',
          icon: 'success'
        });
      }
    });
  },
  
  toggleDataPanel: function() {
    this.setData({
      showDataPanel: !this.data.showDataPanel
    });
    
    if (this.data.showDataPanel) {
      this.getStatisticsData();
    }
  },

  getStatisticsData: function() {
    wx.request({
      url: 'https://api.example.com/shop/statistics',
      method: 'GET',
      header: {
        'Authorization': `Bearer ${app.globalData.token}`
      },
      success: (res) => {
        if (res.data && res.data.statistics) {
          this.setData({
            statistics: res.data.statistics,
          });
        }
      }
    });
  },
  
  // 打开地图选择位置
  chooseLocation: function() {
    wx.chooseLocation({
      success: (res) => {
        // 更新位置信息
        const location = {
          latitude: res.latitude,
          longitude: res.longitude,
          name: res.name,
          address: res.address
        };
        
        app.globalData.location = location;
        this.setData({
          location: location,
          markers: [{
            id: 1,
            latitude: location.latitude,
            longitude: location.longitude,
            width: 30,
            height: 30,
            callout: {
              content: this.data.shopInfo.name || '我的店铺',
              display: 'ALWAYS'
            }
          }]
        });
        
        // 将位置信息上传到服务器
        if (app.globalData.isLogin && app.globalData.token) {
          wx.request({
            url: 'https://api.example.com/shop/location',
            method: 'POST',
            header: {
              'Authorization': `Bearer ${app.globalData.token}`
            },
            data: location
          });
        }
      }
    });
  }
});